<template>
  <view class="addApplyJob">
    <view style=" background: #F3F5FB; padding: 16px;">
      <u-form :model="form" ref="uForm" l>
        <view class="jobTitle">基本信息</view>
        <view class="jobForm">
          <u-form-item label="姓名" prop="name">
            <u-input v-model="form.name" placeholder="请输入姓名" input-align="right" />
          </u-form-item>
          <u-form-item label="性别" prop="gender">
            <u-input
              v-model="form.sex"
              @click="show = true"
              placeholder="请输入性别"
              input-align="right"
              type="select"
            />
            <u-select v-model="show" :list="list" @confirm="confirm" :confirmColor="$store.settings.theme" />
          </u-form-item>
          <u-form-item label="手机号" label-width="130" prop="phone">
            <u-input v-model="form.phone" placeholder="请输入手机号" input-align="right" />
          </u-form-item>
        </view>
        <view class="jobTitle">求职期望</view>
        <view class="jobForm">
          <u-form-item label="工作城市" label-width="130" prop="address">
            <u-input v-model="form.address" placeholder="请输入工作城市" input-align="right" />
          </u-form-item>
          <u-form-item label="擅长技能" label-width="130" prop="skill">
            <u-input
              v-model="form.skill"
              type="select"
              @click="openGoodSkills"
              placeholder="请选择擅长技能"
              input-align="right"
            />
          </u-form-item>
          <!-- <u-form-item label="备注（选填）" label-width="180">
            <u-input v-model="form.remark" placeholder="请输入备注（选填）" input-align="right" />
          </u-form-item>-->
        </view>
        <view class="jobTitle">简历上传(非必填)</view>
        <view class="jobForm">
          <view class="jlsc">你可以点击上传完整简历提高推荐通过率</view>
          <view style="padding-bottom:24px" v-if="uploadShow">
            <view class="shangchuanBoxFlexWwarp">
              <view class="shangchuanBoxFlex">
                <img class="wid56" src="../static/shangchuan.png" alt />
                <view>
                  <view class="uploadTextShow">{{ uploadTextShow }}</view>
                  <!-- <view class="uploadTextShowTime">2020-15-5上传</view> -->
                </view>
              </view>
              <view>
                <u-icon name="more-dot-fill" @click="showdot = true" color="#ACAFC5" size="48"></u-icon>
              </view>
            </view>
          </view>
          <view v-if="!uploadShow">
            <view class="jlscBox">
              <view class="jlscBoxWwidth" @tap="upload('positive')">
                <view>
                  <img class="jlscimage" src="../static/image.png" alt />
                  <view class="jlscText">上传图片简历</view>
                </view>
              </view>
              <view class="jlscBoxWwidth" @tap="chooseFile('positive')">
                <view>
                  <img class="jlscimage1" src="../static/folderadd.png" alt />
                  <view class="jlscText">上传微信文件简历</view>
                </view>
              </view>
            </view>
            <view class="jlsc1">支持pdf、jpg、png、word等文件格式</view>
          </view>
        </view>
        <view>
          <button class="ljtdButton" :disabled="disShow" @click="immediateDelivery">立即投递</button>
        </view>
      </u-form>
      <u-action-sheet :list="listdot" @click="clickDot" v-model="showdot"></u-action-sheet>
    </view>
  </view>
</template>

<script>
import { uploadSiteImg, uploadSiteFile } from "@/services/common";
import { jobSeekersAdd, deliverRecords, resumeTransformation } from "./api";
import { mapState } from "vuex";
export default {
  data() {
    return {
      afterConversionAnnex: "",
      showdot: false,
      listdot: [
        {
          text: "预览"
        },
        {
          text: "删除",
          color: "red"
        }
      ],
      disShow: false,
      uploadShow: false,
      positive: "",
      uploadTextShow: "",
      recruitInfo: {},
      form: {
        name: "",
        gender: "",
        phone: "",
        address: "",
        skill: "",
        remark: ""
      },
      haveResume: false,
      selectFirstUser: {},
      rules: {
        name: [
          {
            required: true,
            message: "请输入姓名",
            trigger: ["change", "blur"]
          }
        ],
        gender: [
          {
            required: true,
            message: "请选择性别",
            trigger: ["change", "blur"]
          }
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: ["change", "blur"]
          },
          {
            validator: (rule, value, callback) => {
              return this.$u.test.mobile(value);
            },
            message: "手机号码不正确",
            trigger: ["change", "blur"]
          }
        ],
        address: [
          {
            required: false,
            message: "请输入地址",
            trigger: ["change", "blur"]
          }
        ],
        skill: [
          {
            required: false,
            message: "请选择擅长技能",
            trigger: ["change", "blur"]
          }
        ]
      },
      show: false,
      list: [
        {
          value: "1",
          label: "男"
        },
        {
          value: "2",
          label: "女"
        }
      ]
    };
  },
  watch: {
    "form.name"() {
      this.uploadTextShow = `${this.form.name}简历已上传`;
    }
  },
  onLoad(e) {
    this.recruitInfo = JSON.parse(e.data);
    const selectFirstUser = JSON.parse(e.selectFirstUser);
    if (selectFirstUser !== null) {
      this.haveResume = true;
      this.form = {
        ...selectFirstUser,
        sex: selectFirstUser.gender === 1 ? "男" : "女"
      };
      if (selectFirstUser.annex) {
        this.uploadShow = true;
        this.positive = selectFirstUser.annex;
        this.afterConversionAnnex = selectFirstUser.afterConversionAnnex;
        this.uploadTextShow = `${this.form.name}简历已上传`;
      } else {
        this.positive = "";
        this.afterConversionAnnex = "";
        this.uploadShow = false;
      }
    } else {
      this.haveResume = false;
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  computed: {
    ...mapState(["user", "jobSeeker"])
  },
  methods: {
    clickDot(index) {
      if (index === 0) {
        if (this.getSrc(this.afterConversionAnnex, ["pdf", "pdfx"])) {
          this.openFile(this.afterConversionAnnex);
        } else {
          uni.navigateTo({
            url: `/applyJob/applyJob/previewImage/previewImage?positive=${this.positive}`
          });
        }
      } else {
        this.chooseUpload();
      }
    },
    getSrc(src, arr) {
      const srcSHow = arr.includes(
        src
          .split("/")
          .slice(-1)[0]
          .split(".")
          .splice(-1)[0]
      );
      return srcSHow;
    },
    openFile(path) {
      wx.downloadFile({
        url: path,
        success: function(res) {
          const filePath = res.tempFilePath;
          wx.openDocument({
            filePath: filePath,
            fileType: "pdf",
            success: function(success) {},
            fail: function(err) {
              // console.log(err);
            }
          });
        }
      });
    },
    chooseUpload() {
      this.uploadShow = false;
      this.positive = "";
      this.afterConversionAnnex = "";
    },

    // 注意返回值为一个数组，单列时取数组的第一个元素即可(只有一个元素)
    confirm(e) {
      this.form.gender = e[0].value;
      this.form.sex = e[0].label;
    },
    immediateDelivery() {
      this.$refs.uForm.validate(valid => {
        if (valid) {
          if (this.haveResume) {
            this.deliverRecords({ id: uni.getStorageSync("jobSeekerId") });
          } else {
            const data = {
              ...this.form,
              annex: this.positive
            };
            this.deliverRecords(data);
            // this.jobSeekersAdd();
          }
        }
      });
    },
    jobSeekersAdd() {
      this.$refs.uForm.validate(valid => {
        if (valid) {
          const data = {
            principalId: uni.getStorageSync("empId"),
            principalType: "emp",
            annex: this.positive,
            afterConversionAnnex: this.afterConversionAnnex,
            empRuleIsOpen: this.recruitInfo.empRuleIsOpen,
            ...this.form
          };
          this.disShow = true;
          jobSeekersAdd(data)
            .then(res => {
              uni.setStorageSync("loginid", res.id);
              this.$store.commit("user/updateUserInfo");
              this.deliverRecords(res);
            })
            .catch(err => {
              // console.log(err);
            });
        } else {
          // console.log("验证失败");
        }
      });
    },
    deliverRecords(res) {
      const data = {
        ...res,
        // talentPoolId: res.id,
        jobSeekerName: this.form.name,
        userId: this.user.id,
        recruitInfoId: this.recruitInfo.recruitInfoId,
        empRule: this.recruitInfo.empRule,
        empMoneyReward: this.recruitInfo.empMoneyReward,
        brokerRule: this.recruitInfo.brokerRule,
        companyUnitId: this.recruitInfo.companyUnitId,
        empRuleIsOpen: this.recruitInfo.empRuleIsOpen,
        sourceId: uni.getStorageSync("empId"),
        sourceType: "emp",
        annex: this.positive,
        afterConversionAnnex: this.afterConversionAnnex
      };
      deliverRecords(data)
        .then(res => {
          uni.showToast({
            title: "操作成功",
            icon: "success",
            duration: 2000
          });
          this.navigateBackFun();
        })
        .catch(err => {
          uni.showToast({
            title: err.msg,
            icon: "success",
            duration: 2000
          });
        });
    },
    navigateBackFun() {
      setTimeout(function() {
        uni.navigateBack();
        this.disShow = false;
      }, 2000);
    },
    openGoodSkills() {
      uni.navigateTo({
        url: `/applyJob/applyJob/goodSkills/goodSkills?skill=${this.form.skill}`
      });
    },
    chooseFile(idx) {
      const temp = {
        src: null,
        url: null,
        name: null,
        ext: null
      };
      // #ifdef MP-WEIXIN
      wx.chooseMessageFile({
        type: "file",
        extension: ["doc", "docx", "pdf"],
        count: 1,
        success: fileRes => {
          const tempFiles = fileRes.tempFiles;
          temp.name = tempFiles[0]["name"];
          const extArr = temp.name.split(".");
          temp.ext = extArr[extArr.length - 1];
          temp.src = this.getExt(temp.ext);
          resumeTransformation(tempFiles[0].path).then(res => {
            if (res.transformationResultUrl) {
              this.afterConversionAnnex = res.transformationResultUrl;
              this.positive = res.transformationFrontUrl;
            } else {
              this.positive = res.transformationFrontUrl;
              this.afterConversionAnnex = res.transformationFrontUrl;
            }
            this.uploadTextShow = `${this.form.name}简历已上传`;
            this.uploadShow = true;
          });
        },
        fail: fileErr => {
          uni.showToast({
            title: fileErr.message,
            icon: "none",
            duration: 2000
          });
        }
      });
      // #endif
      // #ifdef H5
      // #endif
    },
    getExt(ext) {
      if (["xls", "xlsx"].includes(ext)) {
        return "/approval/img/apx-excel.png";
      } else if (["doc", "docx"].includes(ext)) {
        return "/approval/img/apx-word.png";
      } else if (["ppt", "pptx"].includes(ext)) {
        return "/approval/img/apx-ppt.png";
      } else if (["pdf"].includes(ext)) {
        return "/approval/img/apx-pdf.png";
      } else {
        return "/approval/img/apx-unknown.png";
      }
    },
    upload(type) {
      uni.chooseImage({
        count: 1,
        success: imageRes => {
          const tempFilePaths = imageRes.tempFilePaths;
          uni.showLoading({
            title: "文件上传中...",
            mask: true
          });
          uploadSiteImg(tempFilePaths[0])
            .then(res => {
              this.uploadShow = true;
              const urlShow = res[0];
              this.positive = urlShow;
              this.afterConversionAnnex = this.positive;
              this.uploadTextShow = `${this.form.name}简历已上传`;
              uni.hideLoading();
            })
            .catch(err => {
              uni.hideLoading();
              uni.showToast({
                title: err.message,
                icon: "none",
                duration: 1500
              });
            });
        },
        fail: err => {
          uni.showToast({
            title: err.message,
            icon: "none",
            duration: 1500
          });
        }
      });
    }
  }
};
</script>
<style lang="scss">
@import "../../../styles/styles.scss";
@import "./index.scss";
</style>
